package com.tiem_files.controller.login;

import com.tiem_files.common.Constant;
import com.tiem_files.controller.BaseController;
import com.tiem_files.model.User;
import com.tiem_files.service.DeptService;
import com.tiem_files.service.UserService;
import com.tiem_files.service.impl.DeptServiceImpl;
import com.tiem_files.service.impl.UserServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

@WebServlet("/login/*")
public class LoginController extends BaseController {
    private UserService userService=new UserServiceImpl();

    public void toLogin(HttpServletRequest req, HttpServletResponse resp) {

        try {

            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String rememberMe = req.getParameter("rememberMe");
            User user = userService.finByName(username);
            if (user != null) {
                //比较密码
                if (password.equals(user.getPassword())) {
                    //密码正确--登陆成功
                    if (rememberMe != null) {
                        Cookie cookie = new Cookie("uName",username);
                        cookie.setMaxAge(Constant.MAX_COOKIE_TIME);
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                    }
                    //查询用户信息
                    Map<String,Object> map = userService.findUserBaseInfo(username);
                    req.getSession().setAttribute("userBaseInfo",map);
                    req.getSession().setAttribute("myUserId",map.get("user_id").toString());

                    //更新登录时间
                    userService.updateLoginTime(user.getId());

                    resp.sendRedirect(req.getContextPath()+"/assets/html/home.jsp");
                    return;
                }else {
                    req.getSession().setAttribute("loginMsg","密码错误");
                }

            }else {
                req.getSession().setAttribute("loginMsg","用户名不存在");
            }
            //登陆失败--跳回首页
            resp.sendRedirect(req.getContextPath()+"/index.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void register(HttpServletRequest req, HttpServletResponse resp){
        try {
            String email = req.getParameter("email");
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            String password2 = req.getParameter("password2");
            boolean b = userService.checkByEmailOrName( email,username);
            if (!b){
                //不能注册
                req.getSession().setAttribute("registerMsg","用户名或邮箱已被注册");
                resp.sendRedirect(req.getContextPath()+"/register.jsp");
            }else {
                //检查输入的两次密码是否一致
                if (password.equalsIgnoreCase(password2)){
                    //密码相同可以注册,并将数据保存到数据库
                    User user =new User();
                    user.setEmail(email);
                    user.setUsername(username);
                    user.setPassword(password);
                    boolean add = userService.addUser(user);
                    if (add){


                        //添加成功,重定向到登录页面
                        req.getSession().setAttribute("registerMsg","注册成功!");
                        resp.sendRedirect(req.getContextPath()+"/index.jsp");
                    }else {
                        req.getSession().setAttribute("registerMsg","注册失败!");
                        resp.sendRedirect(req.getContextPath()+"/register.jsp");
                    }
                }else {
                    req.getSession().setAttribute("registerMsg","两次密码不一致,请重新输入!");
                    resp.sendRedirect(req.getContextPath()+"/register.jsp");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void checkEmail(HttpServletRequest req, HttpServletResponse resp){
        try {
            String email = req.getParameter("email");
            User user = userService.finByEmail(email);
            String data = "0";
            if (user != null){
                data="1";
            }
            resp.getWriter().write(data);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void checkUser(HttpServletRequest req, HttpServletResponse resp){
        try {
            String username = req.getParameter("username");
            User user = userService.finByName(username);
            String data = "0";
            if (user != null){
                data="1";
            }
            resp.getWriter().write(data);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void sendEmail(HttpServletRequest req, HttpServletResponse resp){
        resp.setCharacterEncoding("utf-8");
        try {
            HttpSession session =req.getSession();
            String email = req.getParameter("email");
            User user =userService.finByEmail(email);
            if (null == user){
                resp.getWriter().write("该邮箱账号不存在");
            }else {
                Object value = session.getAttribute(email);
                if (null == value){
                    //发送邮件
                    String code =userService.sendEmailCode(email);
                    if (code.length()==6){
                        //发送成功 并保存到session
                        session.setAttribute(email,code);
                        session.setMaxInactiveInterval(Constant.MAX_EMAIL_TIME);
                        resp.getWriter().write("发送成功");
                    }else {
                        resp.getWriter().write("发送失败");

                    }
                }else {
                    resp.getWriter().write("邮件已发送成功，请查收");
                }

            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void reset(HttpServletRequest req, HttpServletResponse resp){
        try {
            String email = req.getParameter("email");
            String code = req.getParameter("code");
            String password = req.getParameter("password");
            User user =userService.finByEmail(email);
            if (null == user){
                req.getSession().setAttribute("forgetMsg","该邮箱不存在");
                resp.sendRedirect(req.getContextPath()+"/forget.jsp");
            }else {
                //校验前端发的code和后端保存的code是否一致
                Object value = req.getSession().getAttribute(email);
                if (null == value){
                    req.getSession().setAttribute("forgetMsg","验证码无效");
                    resp.sendRedirect(req.getContextPath()+"/forget.jsp");
                }else {
                    if (value.toString().equals(code)){
                        //相同 可以注册
                        boolean b = userService.resetPassword(email,password);
                        if (b){
                            req.getSession().setAttribute("loginMsg","重置密码成功");
                            resp.sendRedirect(req.getContextPath()+"/index.jsp");
                        }else {
                            req.getSession().setAttribute("loginMsg","重置密码失败");
                            resp.sendRedirect(req.getContextPath()+"/index.jsp");
                        }
                    }else {
                        req.getSession().setAttribute("forgetMsg","验证码不正确");
                        resp.sendRedirect(req.getContextPath()+"/forget.jsp");
                    }
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void logout(HttpServletRequest req, HttpServletResponse resp){
        try {
            Cookie[] cookies = req.getCookies();
            for (Cookie cookie:cookies) {
                if ("uName".equals(cookie.getName())){
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);

                }
            }
            resp.sendRedirect(req.getContextPath() + "/index.jsp");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
